package ru.nsu.ccfit.shumkina.algorithm.graphworks;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Вера
 * Time: 22:11
 * To change this template use File | Settings | File Templates.
 */
public class DotGraphMaker {
    public static Graph restoreMenuGraph(String fileName)
    {
        Graph graph = null;

        try {
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String currLine = br.readLine();
            while (currLine != null && !currLine.equals("}"))
            {
                if (currLine.isEmpty())
                {
                    currLine = br.readLine();
                    continue;
                }
                if (currLine.startsWith("digraph"))
                {
                    graph = new Graph();
                    currLine = br.readLine();
                    continue;
                }
                currLine = currLine.replace(";", "");
                currLine = currLine.replace("\t", "");
                currLine = currLine.replace(" ", "");

                if (currLine.contains("->"))
                {
                    String[] pages = currLine.split("->");
                    if (pages.length < 2)
                    {
                        currLine = br.readLine();
                        continue;
                    }
                    if (!graph.pages.containsKey(pages[0]))
                        graph.pages.put(pages[0], new Page(pages[0]));
                    if (!graph.pages.containsKey(pages[1]))
                        graph.pages.put(pages[1], new Page(pages[1]));

                    Page pageFrom = graph.pages.get(pages[0]);
                    Page pageTo = graph.pages.get(pages[1]);


                    pageFrom.children.put(pages[1], pageTo);
                    pageTo.parents.put(pages[0], pageFrom);

                    graph.arcNames.put(pages[0] + " -> " + pages[1], pages[1]);
                }
                else
                {
                    graph.pages.put(currLine, new Page(currLine));
                }
                currLine = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        return graph;
    }
}
